//
//  SelectEmployeeVC.swift
//  Employee
//
//  Created by swordjoy on 2017/3/29.
//  Copyright © 2017年 remotevillage. All rights reserved.
//


import UIKit
import Moya
import IQKeyboardManagerSwift

class SelectEmployeeVC: BaseVC {

  // 属性传值,用于转交工单
  var orderId: String!
  
  var didSuccess: VoidClosure?
  
  // 选中转交人的id
  fileprivate var selectStaffId: String = ""
  
  fileprivate var sortChatUsers: [[ChatUser]] = []
  fileprivate var titles: [String] = []
  
  fileprivate var searchView: SJSearchBar!
  fileprivate var tableView: UITableView!
  
    fileprivate var topLabel: UILabel!
    fileprivate var bottomLabel: UILabel!
  fileprivate var okButton: UIButton!
  
  fileprivate var canclePull: Cancellable?
    fileprivate lazy var sectionTitleView: UILabel = {
        let label = UILabel()
        label.textAlignment = .center;
        label.font = UIFont.systemFont(ofSize: 60)
        label.textColor = GlobalConfig.BGSkyBlueColor
        label.backgroundColor = GlobalConfig.BGWhiteColor
        label.layer.cornerRadius = 6;
        label.layer.borderWidth = 1.0 / UIScreen.main.scale;
        label.layer.borderColor = UIColor.groupTableViewBackground.cgColor;
        label.isHidden = true;
        self.view.addSubview(label)
        label.snp.makeConstraints({ (make) in
            make.center.equalToSuperview()
            make.width.height.equalTo(100)
        })
        return label
    }()
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    view.backgroundColor = GlobalConfig.BGWhiteColor
    title = "工单转交给"

    create()
    
    pullData()
    
    if let _ = tableView.indexPathForSelectedRow {
      okButton.isSelected = true
    }
    
  }
  
  override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    
    GlobalConfig.baiduStatisticsPageViewStart("转交选择员工")
  }
  
  override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    GlobalConfig.baiduStatisticsPageViewEnd("转交选择员工")
  }
  
  deinit {
    
    // 没有请求完退出,取消请求
    if let cancle = canclePull {
      
      cancle.cancel()
      
    }
    
  }
  
}

// MARK: - action

extension SelectEmployeeVC {
  @objc fileprivate func cancleAction() {
    
    let _ = navigationController?.popViewController(animated: true)
    
  }
  
  @objc fileprivate func okAction() {
    
    SJApp.showHUD()
    let _ = WorkorderRequest.shared.handleOrder(type: "TRANSFER", workOrderId: orderId, staffId: selectStaffId, replyContent: "", images: "", success: {
      SJToast.successShow("转交成功")
      let _ = self.navigationController?.popViewController(animated: true)
      if let temp = self.didSuccess { temp() }
    }) {  }
    
  }
}

// MARK: - fileprivate

extension SelectEmployeeVC {
  
  fileprivate func pullData() {
    
    canclePull = UserRequest.shared.getUserAddressBook { (chatUsers) in
      
      let sortData = AddressBookHelper.sortUser(chatUsers: chatUsers)
      self.sortChatUsers = sortData.0
      self.titles = sortData.1
      self.tableView.reloadData()
      
      SJCache.chatUsers = chatUsers
      
    }
    
  }
  
  fileprivate func create() {
    
//    let cancleButton = UIButton(frame: CGRect(x: 0, y: 0, width: 44, height: 44))
//    cancleButton.setTitle("取消", for: .normal)
//    cancleButton.setTitleColor(GlobalConfig.BGSkyBlueColor, for: .normal)
//    cancleButton.titleLabel?.font = GlobalConfig.system16Font
//    cancleButton.addTarget(self, action: #selector(cancleAction), for: .touchUpInside)
//    let cancleItem = UIBarButtonItem(customView: cancleButton)
//    navigationItem.leftBarButtonItem = cancleItem
    self.addBackTitleItem(title: "取消")
    
    okButton = ObserveButton(frame: CGRect(x: 0, y: 0, width: 44, height: 44))
    okButton.setTitle("确定", for: .normal)
    okButton.titleLabel?.font = GlobalConfig.system16Font
    okButton.addTarget(self, action: #selector(okAction), for: .touchUpInside)
    okButton.isSelected = false
    let okItem = UIBarButtonItem(customView: okButton)
    navigationItem.rightBarButtonItem = okItem
    

    searchView = SJSearchBar()
    searchView.placeholder = "用户名称/手机号"
    searchView.isCancleButton = false
    searchView.delegate = self
    view.addSubview(searchView)
    
    
    tableView = UITableView()
    tableView.backgroundColor = UIColor.clear
    tableView.frame = CGRect(x: 0, y: 44, width: UIScreen.width, height: UIScreen.height - 108)
    tableView.delegate = self
    tableView.dataSource = self
    tableView.separatorStyle = .none
    tableView.sectionIndexColor = GlobalConfig.BGSkyBlueColor
    tableView.sectionIndexBackgroundColor = UIColor.clear
    tableView.rowHeight = SelectEmployeeCell.height
    tableView.sectionHeaderHeight = 37
    let footer = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.width, height: 10))
    footer.backgroundColor = GlobalConfig.BGWhiteColor
    tableView.tableFooterView = footer
    tableView.register(SelectEmployeeCell.self, forCellReuseIdentifier: SelectEmployeeCell.identifier)
    view.addSubview(tableView)
    
    
    topLabel = UILabel()
    view.addSubview(topLabel)
    topLabel.font = GlobalConfig.system15Font
    topLabel.textColor = GlobalConfig.BGSkyBlueColor
    topLabel.snp.makeConstraints { (make) in
        
        make.centerX.equalToSuperview()
        make.top.equalTo(100)
        
    }
    
    bottomLabel = UILabel()
    view.addSubview(bottomLabel)
    bottomLabel.font = GlobalConfig.system15Font
    bottomLabel.textColor = GlobalConfig.BGSkyBlueColor
    bottomLabel.numberOfLines = 0
    bottomLabel.textAlignment = .center
    bottomLabel.snp.makeConstraints { (make) in
        
        make.left.equalTo(50)
        make.right.equalTo(-50)
        make.centerX.equalToSuperview()
        make.top.equalTo(topLabel.snp.bottom).offset(5)
        
    }
    
  }
}

// MARK: - 

extension SelectEmployeeVC: SJSearchBarDelegate {
  
  func didEndSearch() {
    
  }
  
  func didBeaginSearch() {
    
  }
  
  func didChange(text: String) {
    
    let users = SJCache.chatUsers
    
    if text.isEmpty {
      
        self.topLabel.isHidden = true
        self.bottomLabel.isHidden = true
        self.tableView.isHidden = false
      selectStaffId = ""
      okButton.isSelected = true
      let sortData = AddressBookHelper.sortUser(chatUsers: users)
      self.sortChatUsers = sortData.0
      self.titles = sortData.1
      self.tableView.reloadData()
      
      return
      
    }
    
    
    let filterUsers = users.filter { (user) -> Bool in
      
      if user.nickname.contains(text) {
        return true
      }
      else if user.phoneNumber.contains(text) {
        return true
      }
      return false
      
    }
    
    let sortData = AddressBookHelper.sortUser(chatUsers: filterUsers)
    if sortData.0.count <= 0 {
        self.topLabel.text = "哎呀!"
        self.bottomLabel.text = "没有找到“\(self.searchView.text)”的相关用户"
        self.topLabel.isHidden = false
        self.bottomLabel.isHidden = false
        self.tableView.isHidden = true
        return
    } else {
        self.topLabel.isHidden = true
        self.bottomLabel.isHidden = true
        self.tableView.isHidden = false
    }
    self.sortChatUsers = sortData.0
    self.titles = sortData.1
    self.tableView.reloadData()
    
  }
  
}

// MARK: - UITableViewDataSource

extension SelectEmployeeVC : UITableViewDataSource {
  func numberOfSections(in tableView: UITableView) -> Int { return titles.count }
  
  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return sortChatUsers[section].count
  }
  
  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: SelectEmployeeCell.identifier) as! SelectEmployeeCell
    cell.selectionStyle = .none
    cell.model = sortChatUsers[indexPath.section][indexPath.row]
    
    return cell
  }
}

// MARK: - UITableViewDelegate

extension SelectEmployeeVC : UITableViewDelegate {
  
  func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let view = SectionV(frame: CGRect(x: 0, y: 0, width: UIScreen.width, height: 37))
    view.title = titles[section]
    return view
  }
  
  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if sortChatUsers[indexPath.section][indexPath.row].id == User.staffId {
      selectStaffId = ""
      okButton.isSelected = false
      SJToast.failShow("不能转交给自己")
      return
    }
    
    selectStaffId = sortChatUsers[indexPath.section][indexPath.row].id
    okButton.isSelected = true
  }
  
  func sectionIndexTitles(for tableView: UITableView) -> [String]? { return titles }

    func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
        self.showSectionTitle(title)
        return index
    }
    
    func showSectionTitle(_ title:String) {
        self.sectionTitleView.text = title
        self.sectionTitleView.isHidden = false
        self.sectionTitleView.alpha = 1
        let t = DispatchTime.now() + 1
        DispatchQueue.main.asyncAfter(deadline: t) {
            UIView.animate(withDuration: 0.3, animations: {
                self.sectionTitleView.alpha = 0
            }, completion: { (finished) in
                self.sectionTitleView.isHidden = true
            })
        }
    }
}
